package com.jiang.jetpackdemo.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.google.gson.Gson
import com.jiang.jetpackdemo.*
import com.jiang.jetpackdemo.activity.PlayVideoActivity
import com.jiang.jetpackdemo.adapter.MyOnClickListener
import com.jiang.jetpackdemo.adapter.VideoAdapter
import com.jiang.jetpackdemo.http.RetrofitManager
import com.jiang.jetpackdemo.model.VideoRecommendInfo
import com.jiang.jetpackdemo.utils.SPUtil

import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.Random

class VideoRecommendFragment : Fragment() {

    companion object {
        fun newInstance() = VideoRecommendFragment()
        const val INTENT_KEY = "VideoRecommendFragment_KEY"
        const val BOUND = 18_0000
    }

    private lateinit var viewModel: VideoRecommendViewModel
    private lateinit var adapter: VideoAdapter
    private val random: Random = Random()
    private lateinit var spUtil: SPUtil

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.video_recommend_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        viewModel = ViewModelProvider(this).get(VideoRecommendViewModel::class.java)
        initView()
        viewModel.videoInfoListSize.observe(
            activity!!,
            Observer { adapter.notifyDataSetChanged() })
        spUtil = SPUtil(context!!)
        readCache()
    }

    private fun readCache() {
        val l = System.currentTimeMillis()
        spUtil.getVideoRequestCache(object : SPUtil.CallBack {
            override fun onFinish(cache: String) {
                if (spUtil.isOutOfDate(SPUtil.KEY_VIDEO_DATE) || cache.isEmpty()) {
                    getData(random.nextInt(BOUND))
                } else {
                    val info = Gson().fromJson(cache, VideoRecommendInfo::class.java)
                    val result = info.result
                    if (result.isNullOrEmpty()) {
                        getData(random.nextInt(BOUND))
                    } else {
                        viewModel.resetVideoInfoList(result)
                        Log.d("readCache", "${System.currentTimeMillis() - l}ms")
                    }
                }
            }
        })
    }

    private fun initView() {
        srl.setOnRefreshListener {
            getData(random.nextInt(BOUND))
        }
        adapter = VideoAdapter(
            context!!,
            viewModel.videoInfoList.value!!,
            R.layout.item_rv
        )
        rv.adapter = adapter
        rv.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)

        adapter.setOnClickListener(object : MyOnClickListener {
            override fun onClick(pos: Int) {
                jumpWithBean(pos)
            }
        })
    }

    private fun jumpWithBean(pos: Int) {
        val value =
            if (viewModel.videoInfoListSize.value!! >= pos) viewModel.videoInfoList.value else null
        val bean = value?.get(pos)
        val intent = Intent(context, PlayVideoActivity::class.java)
        intent.putExtra(INTENT_KEY, Gson().toJson(bean))
        startActivity(intent)
    }

    private fun getData(seed: Int) {
        RetrofitManager.getVideoRecommend(seed, object : Callback<VideoRecommendInfo> {
            override fun onFailure(call: Call<VideoRecommendInfo>, t: Throwable) {
                Toast.makeText(context, t.message, Toast.LENGTH_SHORT).show()
                if (srl.isRefreshing) srl.isRefreshing = false
            }

            override fun onResponse(
                call: Call<VideoRecommendInfo>,
                response: Response<VideoRecommendInfo>
            ) {
                if (response.isSuccessful) {
                    val result = response.body()?.result
                    if (!result.isNullOrEmpty() && result.size > 1) {
                        result.removeAt(0)
                        viewModel.resetVideoInfoList(result)
                        if (srl.isRefreshing) srl.isRefreshing = false
                        val cache =
                            VideoRecommendInfo()
                        cache.result = result
                        spUtil.setVideoRequestCache(Gson().toJson(cache))
                    }
                }
            }

        })
    }

}
